package org.microservice.auth.exception;

import org.microservice.common.util.CustomRuntimeException;
import org.microservice.common.util.R;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA.
 * User: 齐丹枫
 * Date: 2018/6/22
 * Time: 8:53
 * To change this template use File | Settings | File Templates.
 * Description:
 */
@Component("customWebResponseExceptionTranslator")
public class CustomWebResponseExceptionTranslator  implements WebResponseExceptionTranslator {


    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {

        if(e instanceof OAuth2Exception){
            OAuth2Exception oAuth2Exception = (OAuth2Exception) e;
            return ResponseEntity
                    .status(oAuth2Exception.getHttpErrorCode())
                    .body(new CustomOauthException(oAuth2Exception.getMessage()));
        }else{
            Throwable cause = e.getCause();
            if(cause instanceof CustomRuntimeException){
                return generateResponseEntity(R.error(cause.getMessage()));
            }
            return  generateResponseEntity(R.error());
        }

    }


    private ResponseEntity generateResponseEntity(R r){
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        ResponseEntity<R> response = new ResponseEntity<R>(r, headers,
                HttpStatus.valueOf(500));
        return  response;
    }


}
